import React from 'react';
import uuid from 'uuid';

import CreateBar from '../CreateBar';
import List from '../List';
import ItemShowLayer from '../ItemShowLayer';
import ItemEditLayer from '../ItemEditLayer';


import './style.scss';

export default class App extends React.Component {
	constructor(props){
		super(props);

		this.state = {
			items: [],
			selectedId: null,
			editing: false,
		};

		this.selectItem = this.selectItem.bind(this);
		this.addItem = this.addItem.bind(this);
		this.saveItem = this.saveItem.bind(this);

		this.editItem = this.editItem.bind(this);
		this.deleteItem = this.deleteItem.bind(this);

		this.cancelEdit = this.cancelEdit.bind(this);
	}

	addItem(){
		this.setState({
			editing: true,
			selectedId: null,
		});
	}

	editItem(itemId){
		this.setState({
			editing: true,
			selectedId: itemId,
		})
	}

	cancelEdit(){
		this.setState({
			editing: false,
		});
	}
	saveItem(obj){
		let items = this.state.items;

		if(!obj.id){

			//add
			items = [...items,
				{...obj,
				id: uuid.v4(),
				time: new Date().getTime(),
				}]
		}else{
			//edit
			items = items.map(
				(exist) => {
					if(exist.id === obj.id){
                        return {...exist, ...obj}
					}else{
						return exist
					}
				})
		}
		console.log(items);

		this.setState({
			items,
			selectedId: obj.id,
			editing: false,
		});
	}

	deleteItem(id){
		if(!id){
			return;
		}

		this.setState({
			items: this.state.items.filter((el) => {el.id != id})
		});
	}



	selectItem(id) {
		if(id === this.state.selectedId) {
			return;
		}

		this.setState({
			selectedId: id,
			editing: false,
		});
	}



	render() {
		const {items, selectedId, editing} = this.state;
		const selected = selectedId && items.find(item => item.id === selectedId);
		const mainPart = editing 
		? (
			<ItemEditLayer item={selected} onSave={this.saveItem} onCancel={this.cancelEdit}/>
			)
		: (
			<ItemShowLayer item={selected} onEdit={this.editItem} onDelete={this.deleteItem}/>
			);

		return (
			<section className="deskmark-component" >
				<nav className="navbar navbar-fixed-top navbar-dark bg-inverse">
					<a className="navbar-brand" href="#">Deskmark App</a>
				</nav>
				<div className="container">
					<div className="row">
						<div className="col-md-4 list-group">
							<CreateBar onClick={this.addItem} />
							<List items={this.state.items} onSelect={this.selectItem}/>
						</div>
						{mainPart}
					</div>
				</div>
			</section>
			)
	}
}